$(function () {
    /*时间转换格式函数*/
    function formatDate(now) {
        var year = now.getFullYear(),
            month = now.getMonth() + 1,
            date = now.getDate(),
            hour = now.getHours(),
            minute = now.getMinutes(),
            second = now.getSeconds();

        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }

    //判断session
    $.ajax({
        url: '/session',
        dataType: "json",
        type: "post",
        success: function (data) {
            if (data.code == "0") {

            } else if (data.code == "1") {
                $("#tip").empty().html("<li id=\"register\"><a href=\"register.html\">注册</a></li>\n" +
                    "<li id=\"login\"><a href=\"login.html\">登陆</a></li>");
            }

        },
        error: function (error) {
            alert("请求错误！");
            window.location.href = 'login.html';
        }

    });
    //select
    $.ajax({
        url: '/food/type',
        dataType: "json",
        type: "post",
        success: function (data) {
            var types = data.data;
            var listring = "<li value='0' style='background:#F3726D '>所有</li>";
            for (var i in types) {
                var jsonObj = types[i];
                listring += "<li value=\'" + jsonObj.typeId + "\'>" + jsonObj.typeName + "</li>";
                $("#type").html(listring);
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    });
    var page = 1;
    var type = 0;
    //自动加载所有菜品
    $.ajax({
        url: '/food/page',
        dataType: "json",
        type: "post",
        data: {
            pageNum: page,
            pageSize: 12,
            type: 0,
            foodName: function () {
                return $('#searchFood').val();
            }
        },
        success: function (data) {
            $("#foodList").empty();
            var types = data.data.list;
            var imgstring = "";
            for (var i in types) {
                var jsonObj = types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                $("#foodList").append(
                    "<div  class='col-md-3' >" +
                    "<a data-whatever=" + jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\"><div class='bgimg' style='background-image: url(" + "http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t5" + ")'></div>" +
                    "<div class='foodtip'>" +
                    "<div class='imgname'>" + jsonObj.foodName + "</div><div class='price'>￥" + jsonObj.price + "</div>" +
                    "</div></a></div>"
                );
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })
    //点击种类
    $('#type').on('click', 'li', function () {
        $(this).css({'background': '#F3726D', 'color': 'white'}).siblings().css({
            'background': 'white',
            'color': 'black'
        });
        page = 1;
        type = $(this).val();
        //自动加载所有菜品
        $.ajax({
            url: '/food/page',
            dataType: "json",
            type: "post",
            data: {
                pageNum: page,
                pageSize: 12,
                type: type,
                foodName: function () {
                    return $('#searchFood').val();
                }
            },
            success: function (data) {
                $("#foodList").empty();
                var types = data.data.list;
                if (types == "") {
                    $("#foodList").append("<div>暂无数据哦，敬请期待</div>");
                } else {
                    var imgstring = "";
                    for (var i in types) {
                        var jsonObj = types[i];
                        // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                        $("#foodList").append(
                            "<div  class='col-md-3' >" +
                            "<a data-whatever=" + jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\">" +
                            "<div class='bgimg' style='background-image: url(" + "http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t5" + ")'></div>" +
                            "<div class='foodtip'>" +
                            "<div class='imgname'>" + jsonObj.foodName + "</div><div class='price'>￥" + jsonObj.price + "</div>" +
                            "</div></a></div>"
                        );
                    }
                }

            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });

    //点击搜索
    $('#searchbtn').click(function () {
        page = 1;

        $.ajax({
            url: '/food/page/result',
            dataType: "json",
            type: "post",
            data: {
                pageNum: page,
                pageSize: 12,
                type: type,
                foodName: function () {
                    return $('#searchFood').val();
                }
            },
            success: function (data) {
                $("#foodList").empty();
                var types = data.data.list;
                if (types == "") {
                    $("#foodList").append("<div>暂无数据哦，敬请期待</div>");
                } else {
                    var imgstring = "";
                    for (var i in types) {
                        var jsonObj = types[i];
                        // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                        $("#foodList").append(
                            "<div  class='col-md-3' >" +
                            "<a data-whatever=" + jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\"><div class='bgimg' style='background-image: url(" + "http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t5" + ")'></div>" +
                            "<div class='foodtip'>" +
                            "<div class='imgname'>" + jsonObj.foodName + "</div><div class='price'>￥" + jsonObj.price + "</div>" +
                            "</div></a></div>"
                        );
                    }
                }

            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });

    $('#Pagination ul li a').click(function () {
        if ($(this).attr("id") == "beginPage") {
            page = 1;
            $(this).attr("value", page);
        } else if ($(this).attr("id") == "previous") {
            page--;
            if (page <= 1) {
                page = 1;
            }
            $(this).attr("value", page);
        } else if ($(this).attr("id") == "next") {
            page++;
            $(this).attr("value", page);
        }
        $.ajax({
            url: '/food/page',
            dataType: "json",
            type: "post",
            data: {
                pageNum: page,
                pageSize: 12,
                type: type,
                foodName: function () {
                    return $('#searchFood').val();
                }
            },
            success: function (data) {
                $("#foodList").empty();
                var types = data.data.list;
                if (types == "") {
                    page--;
                    alert("已经到底啦...再逛逛吧");
                    $.ajax({
                        url: '/food/page',
                        dataType: "json",
                        type: "post",
                        data: {
                            pageNum: page,
                            pageSize: 4,
                            type: type,
                            foodName: function () {
                                return $('#searchFood').val();
                            }
                        },
                        success: function (data) {
                            $("#foodList").empty();
                            var types = data.data.list;
                            var imgstring = "";
                            for (var i in types) {
                                var jsonObj = types[i];
                                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                                $("#foodList").append(
                                    "<div  class='col-md-3' >" +
                                    "<a data-whatever=" + jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\"><div class='bgimg' style='background-image: url(" + "http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t5" + ")'></div>" +
                                    "<div class='foodtip'>" +
                                    "<div class='imgname'>" + jsonObj.foodName + "</div><div class='price'>￥" + jsonObj.price + "</div>" +
                                    "</div></a></div>"
                                );
                            }
                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })
                }
                var imgstring = "";
                for (var i in types) {
                    var jsonObj = types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $("#foodList").append(
                        "<div  class='col-md-3' >" +
                        "<a data-whatever=" + jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\"><div class='bgimg' style='background-image: url(" + "http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t5" + ")'></div>" +
                        "<div class='foodtip'>" +
                        "<div class='imgname'>" + jsonObj.foodName + "</div><div class='price'>￥" + jsonObj.price + "</div>" +
                        "</div></a></div>"
                    );
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        return false;
    });


    //    绑定模态框展示的方法
    $("#myModal").on("show.bs.modal", function (e) {
//        获得点击打开的按钮
        var button = $(e.relatedTarget)
//        根据标签获得按钮传入的参数
        var foodId = button.data("whatever")
//        获得模态框本身
        var modal = $(this)

        $.ajax({
            url: '/food/show/' + foodId,
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                if (data.code = "0") {
                    modal.find(".modal-body #foodid").text(foodId);
                    modal.find(".modal-body #price").text(data.data.price);
                    modal.find(".modal-body #leftimg").css({
                        "background": "url(\"http://ozul99g6g.bkt.clouddn.com/" + data.data.foodImg + "/t5\")",
                        "background-size": "100%",
                        "background-repeat": "no-repeat"
                    });
                    // 更改body里input的值
                    modal.find(".modal-body #modalName").css({"margin-left": "20px"}).text("名称：" + data.data.foodName);
                    modal.find(".modal-body #modalPrice").css({"margin-left": "20px"}).text("价格：￥" + data.data.price);
                    modal.find(".modal-body #modalCalorie").css({"margin-left": "20px"}).text("卡路里：" + data.data.calorie);
                    modal.find(".modal-body #modalRemarks").text("简介：" + data.data.remarks);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        });
    })

    $("#addCart").click(function () {
        $.ajax({
            url: '/cart/put',
            dataType: "json",
            type: "post",
            data: {
                foodId: $("#foodid").text(),
                price: $("#price").text(),
                buyNumber: $("#num").val()
            },
            success: function (data) {
                if (data.code == "0") {
                    alert("添加购物车成功");
                } else {
                    alert("请先登录");
                    window.location.href = 'login.html';
                }
            }
        })

    })


    $.ajax({
        url: '/cart',
        dataType: "json",
        type: "post",
        success: function (data) {
            $("#cartList table tbody").empty();
            var types = data.data;
            var imgstring = "";
            for (var i in types) {
                var jsonObj = types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                $("#cartList table tbody").append("<tr>" +
                    "<td class='box'><input class='cbox'  type='checkbox' value=" + jsonObj.cartId + " input-lg/></td>" +
                    "<td><img src=\"http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t3\"/></td>" +
                    "<td>" + jsonObj.foodName + "</td>" +
                    "<td>" + jsonObj.buyNumber + "</td>" +
                    "<td>￥" + jsonObj.price + "</td>" +
                    "<td>￥" + jsonObj.totalPrice + "</td>" +
                    "<td>" + formatDate(new Date(jsonObj.lastUpdate)) + "</td>" +
                    "<td>" +
                    "<button class=\'btn btn-default deleteFood\' id=\'btnd\'  value=" + jsonObj.cartId + ">删除</button></td>" +
                    "</tr>");
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })
    var time = 0;
    $("#checkall").click(function () {

        if (time == 0) {
            $(".cbox").attr("checked", true);
            time = 1;
        } else if (time == 1) {
            $(".cbox").attr("checked", false);
            time = 0;
        }

    })

    //删除订单
    $('tbody').on('click', '.deleteFood', function () {
        var cartId = $(this).val();
        $.ajax({
            url: '/cart/delete/' + cartId,
            dataType: "json",
            type: "post",
            success: function (data) {
                alert("删除成功");
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });
    //删除选中项
    $('.btn-danger').click(function () {
        // 获取所有选中的checked框
        var option = $(":checked");
        var checkedId = "";
        var boo = true;
        //拼接除全选框外,所有选中的id,
        for (var i = 0, len = option.length; i < len; i++) {
            if (boo) {
                if (option[i].id == 'checkall') {
                    boo = true;
                } else {
                    boo = false;
                    checkedId += option[i].value;
                }
            } else {
                checkedId += "," + option[i].value;
            }
        }
        if (checkedId.charAt(checkedId.length - 1) == 'n') {
            checkedId = checkedId.substring(0, checkedId.length - 3);
        }
        $.ajax({
            url: '/cart/delete/',
            dataType: "json",
            type: "post",
            data: {
                "checkedId": checkedId
            },
            success: function (data) {
                alert("删除成功");
            },
            error: function (error) {
                alert("请求错误！");
            }

        })

    });

    $.ajax({
        url: '/user',
        dataType: "json",
        type: "post",
        success: function (data) {
            $("#addressList #xg #xga").empty();
            var userId = data.data;
            // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
            $("#addressList #xg #xga").append("<div>" +
                "<button class='btn btn-primary' data-whatever=" + userId + " data-toggle=\"modal\" data-target=\"#myModal2\">修改</button>"
                + "</div>"
            );

        },
        error: function (error) {
            alert("请求错误！");
        }
    });
    //模态框

    //    绑定模态框展示的方法
    $("#myModal2").on("show.bs.modal", function (e) {
//        获得点击打开的按钮
        var button = $(e.relatedTarget)
//        根据标签获得按钮传入的参数
        var userId = button.data("whatever")
//        获得模态框本身
        var modal = $(this)

        $.ajax({
            url: '/user/show/' + userId,
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                if (data.code = "0") {
                    modal.find(".modal-body #addressInfo #userId").val(userId);
                    modal.find(".modal-body #addressInfo #phone").val(data.data.phone);
                    modal.find(".modal-body #addressInfo #username").val(data.data.username);
                    // 更改body里input的值
                    // modal.find(".modal-body #modalName").text(data.data.foodName);
                    // modal.find(".modal-body #modalPrice").text("￥" + data.data.price);
                    // modal.find(".modal-body #modalCalorie").text(data.data.calorie);
                    // modal.find(".modal-body #modalRemarks").text(data.data.remarks);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        });

        $.ajax({
            url: '/schoolAddress',
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                var types = data.data;
                var optionstring = "";
                for (var i in types) {
                    var jsonObj = types[i];
                    optionstring += "<option value=\"" + jsonObj.addressId + "\" >" + jsonObj.name + "</option>";
                    modal.find(".modal-body #schoolAddress").html(optionstring);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }
        });


        //保存地址
        $("#conf").click(function () {
            $.ajax({
                url: '/address/update',
                dataType: "json",
                type: "post",
                data: {
                    userId: function () {
                        return $("#userId").val();
                    },
                    phone: function () {
                        return $("#phone").val();
                    },
                    username: function () {
                        return $("#username").val();
                    },
                    schoolAddress: function () {
                        return $("#schoolAddress").val();
                    },
                    addressDetail: function () {
                        return $("#addressDetail").val();
                    }
                },
                success: function (data) {
                    $('#addresss').empty();
                    $('#addresss').html("宿迁学院|" + $("#addressDetail").val());
                    alert("更新成功");
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        })
    });

    //查询地址
    $.ajax({
        url: '/address',
        dataType: "json",
        type: "post",
        success: function (data) {
            if (data.code == "0") {
                $('#addresss').empty();
                $('#addresss').html("宿迁学院|" + data.data.addressDetail);
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    });

    //结算
    $('#payfor').click(function () {
        //查询地址
        $.ajax({
            url: '/address',
            dataType: "json",
            type: "post",
            success: function (data) {
                if (data.code == "1") {
                    alert("请填写地址!")
                } else {
                    // 获取所有选中的checked框
                    var option = $(":checked");
                    var checkedId = "";
                    var boo = true;
                    //拼接除全选框外,所有选中的id,
                    for (var i = 0, len = option.length; i < len; i++) {
                        if (boo) {
                            if (option[i].id == 'checkall') {
                                boo = true;
                            } else {
                                boo = false;
                                checkedId += option[i].value;
                            }
                        } else {
                            checkedId += "," + option[i].value;
                        }
                    }
                    if (checkedId.charAt(checkedId.length - 1) == 'n') {
                        checkedId = checkedId.substring(0, checkedId.length - 3);
                    }
                    //添加订单
                    $.ajax({
                        url: '/cart/checked',
                        dataType: "json",
                        type: "post",
                        data: {
                            "checkedId": checkedId
                        },
                        success: function (data) {
                            $(".zyk #ordersinfo .ordersinfoTable tbody").empty();

                            if (data.data.length > 10) {
                                alert("订单过多");
                            }
                            else {
                                $(".zyk").css('display', 'block');
                                var total = 0;
                                for (var a = 0; a < data.data.length; a++) {
                                    var jsonObj = data.data[a];
                                    total = total + jsonObj.totalPrice;
                                    $(".zyk #ordersinfo .ordersinfoTable tbody").append("<tr>" +
                                        "<td>" + jsonObj.foodName + "</td>" +
                                        "<td>" + jsonObj.buyNumber + "</td>" +
                                        "<td>￥" + jsonObj.totalPrice + "</td>");
                                    $(".zyk .total_price").empty();
                                }
                                $(".zyk .total_price").html(total);
                                //添加订单
                                $(".payBtn").click(function () {
                                    if (data.data.length == 0) {
                                        alert("请选择菜品");
                                    }
                                    else {
                                        var r = confirm("确认付款");
                                        if (r == true) {
                                            alert("付款成功！");
                                            //添加订单
                                            $.ajax({
                                                url: '/orders/add',
                                                dataType: "json",
                                                type: "post",
                                                data: {
                                                    "checkedId": checkedId,
                                                    "price": total
                                                },
                                                success: function (data) {
                                                    if (data.code == "0") {
                                                        $.ajax({
                                                            url: '/cart/del',
                                                            dataType: "json",
                                                            type: "post",
                                                            data: {
                                                                "checkedId": checkedId
                                                            },
                                                            success: function (data) {
                                                            },
                                                            error: function (error) {
                                                                alert("请求错误！");
                                                            }

                                                        });
                                                    }
                                                },
                                                error: function (error) {
                                                    alert("请求错误！");
                                                }

                                            });
                                            //添加订单结束
                                        }
                                        else {
                                            alert("已取消！");
                                        }
                                    }

                                })
                                //添加订单结束
                            }


                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })


                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        });
    });
    $('.x').click(function () {
        $(".zyk").css('display', 'none');
    })

    //订单显示
    $.ajax({
        url: '/orders',
        dataType: "json",
        type: "post",
        success: function (data) {
            $("#ordersList table tbody").empty();
            var types = data.data;
            var imgstring = "";
            for (var i in types) {
                var jsonObj = types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                var status = "";
                if (jsonObj.status == 0) {
                    status = "等待商家接单";
                    $(".st").css({"color": "red"});
                }
                else if (jsonObj.status==1) {
                    status = "商家已接单";
                    $(".st").css({"color": "green"});
                } else if (jsonObj.status==2) {
                    status = "配送中";
                    $(".st").css({"color": "green"});
                }
                else if (jsonObj.status == 3) {
                    status = "订单已完成";
                    $(".st").css({"color": "green"});
                }
                $("#ordersList table tbody").append("<tr>" +
                    "<td >" + jsonObj.ordersId + "</td>" +
                    "<td>" + jsonObj.phone + "</td>" +
                    "<td>" + jsonObj.username + "</td>" +
                    "<td>￥" + jsonObj.price + "</td>" +
                    "<td>" + jsonObj.addressDetail + "</td>" +
                    "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                    "<td class=\'st\'>" + status + "</td>" +
                    "<td>" +
                    "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                    "</tr>");
                if (status == "等待商家接单") {
                    $(".st").css({"color": "red"});
                }
                else if (status == "商家已接单") {
                    $(".st").css({"color": "green"});
                }
                else if (status == "配送中") {
                    $(".st").css({"color": "green"});
                }else if (status == "订单已完成") {
                    $(".st").css({"color": "green"});
                }
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })

    //显示详情
    $('#ordersList table tbody').on('click', '.ordersDetail', function () {
        var ordersId = $(this).val();
        $.ajax({
            url: '/ordersItem/',
            dataType: "json",
            type: "post",
            data: {
                "ordersId": ordersId
            },
            success: function (data) {
                $(".zyk #ordersIteminfo .ordersItemTable tbody").empty();
                var types = data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj = types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $(".zyk #ordersIteminfo .ordersItemTable tbody").append("<tr>" +
                        "<td>" + jsonObj.foodName + "</td>" +
                        "<td>" + jsonObj.buyNumber + "</td>" +
                        "<td>￥" + jsonObj.totalPrice + "</td></tr>");
                }
                $(".zyk").css('display', 'block');
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });

    function searchTop() {
        $.ajax({
            url: '/orders/item/top',
            dataType: "json",
            type: "post",
            success: function (data) {
                $(".recommendTable tbody").empty();
                var types = data.data;
                var imgstring = "";
                for (var i in types) {
                    var j=parseInt(i)+1;
                    var jsonObj = types[i];
                    $(".recommendTable tbody").append(
                        "<tr>" +
                        "<td><strong>" +j + "</strong></td>" +
                        "<td><a data-whatever="+ jsonObj.foodId + " data-toggle=\"modal\" data-target=\"#myModal\">"+ jsonObj.name + "</a></td></tr>"
                    );
                }

            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    }
    searchTop();
})